package com.shihan.rabbitmq.advancedfeatures.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description RabbitMQ 的配置类，只需要声明 Queue 和 Exchange，并进行绑定即可；
 * @Author shihan
 * @Date 2021/1/2 11:43
 * @Version 1.0
 */
@Configuration
public class RabbitMQConfig {

    public static final String EXCHANGE_NAME_DIRECT = "exc.direct.name";

    public static final String QUEUE_NAME = "queue.name";

    public static final String BINDING_KEY = "direct.key";

    @Bean
    public Queue getQueue() {
        return new Queue(QUEUE_NAME, false, false, false, null);
    }

    @Bean
    public Exchange getExchange() {
        return new DirectExchange(EXCHANGE_NAME_DIRECT, false, false, null);
    }

    @Bean
    public Binding getBinding() {
        return BindingBuilder.bind(getQueue()).to(getExchange()).with(BINDING_KEY).noargs();
    }

    //=======================================================================

    public static final String QUEUE_NAME_TTL = "queue.name.ttl.demo";

    public static final String BINDING_KEY_TTL = "key.ttl.demo";

    @Bean
    public Queue getTTLQueue() {
        // Queue TTL 相关的参数设置 Map
        HashMap<String, Object> queueArguments = new HashMap<>();
        // 消息队列中的消息，过期时间为 30 秒！
        queueArguments.put("x-message-ttl", 30 * 1000);
        // 如果当前消息队列没有消费者，那么 60 秒后，当前消息队列就会过期！
        queueArguments.put("x-expires", 60 * 1000);

        return new Queue(QUEUE_NAME_TTL, true, false, false, queueArguments);
    }

    @Bean
    public Binding getTTLBinding() {
        Binding binding = BindingBuilder.bind(getTTLQueue()).to(getExchange()).with(BINDING_KEY_TTL).noargs();
        return binding;
    }

}
